﻿using BCCommon;
using BCCommon.Enums;
using BCData.TMS.WorryFreeMoveSuiteConfig;
using BCDto.TMS.WorryFreeMoveSuiteConfig;
using BCEntity.TMS.WorryFreeMoveSuiteConfig;
using BCEntity.Common.EntityNameConst;
using BCService.Utils;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using BCDto.Sim.Admin.Admin;
using BCData.TMS.WorryFreeMoveSuiteConfigTemplate;
using BCData.TMS.VehicleBusinessMapping;
using BCData.TMS.VehicleSuiteBusinessConfig;
using BCCommon.TMS.Transport;
using BCDto.TMS.Agent.AgentAreaRecord;

namespace BCService.TMS.WorryFreeMoveSuiteConfig
{
	public class WorryFreeMoveSuiteConfigService : IWorryFreeMoveSuiteConfigService
	{
		private readonly IDatabaseContext databaseContext;
		private readonly IRedisService redisService;
		private readonly IWorryFreeMoveSuiteConfigData worryFreeMoveSuiteConfigData;
		private readonly IVehicleBusinessMappingData vehicleBusinessMappingData;
		private readonly IVehicleSuiteBusinessConfigData vehicleSuiteBusinessConfigData;
		private readonly string key = string.Format("{0}", EntityNameConst.WorryFreeMoveSuiteConfigEntity);

		public WorryFreeMoveSuiteConfigService(IDatabaseContext databaseContext,
			IRedisService redisService,
			IWorryFreeMoveSuiteConfigData worryFreeMoveSuiteConfigData,
			IVehicleBusinessMappingData vehicleBusinessMappingData,
			IVehicleSuiteBusinessConfigData vehicleSuiteBusinessConfigData)
		{
			this.databaseContext = databaseContext;
			this.redisService = redisService;
			this.worryFreeMoveSuiteConfigData = worryFreeMoveSuiteConfigData;
			this.vehicleBusinessMappingData = vehicleBusinessMappingData;
			this.vehicleSuiteBusinessConfigData = vehicleSuiteBusinessConfigData;
		}

		#region 检查无忧搬家套餐配置是否存在
		public bool Exists(int worryFreeMoveSuiteConfigId)
		{
			return this.worryFreeMoveSuiteConfigData.Exists(worryFreeMoveSuiteConfigId).GetAwaiter().GetResult();
		}
		#endregion

		#region 添加无忧搬家套餐配置
		public WorryFreeMoveSuiteConfigDto Add(AdminDto adminDto,WorryFreeMoveSuiteConfigRequestDto requestDto)
		{
            if (adminDto.AgentRecord == null)
            {
				throw new ArgumentException("非代理商无法执行此操作!");
            }
            if (!this.vehicleBusinessMappingData.Exists(requestDto.VehicleBusinessMappingId).GetAwaiter().GetResult())
            {
				throw new ArgumentException("车辆业务配置信息不存在!");
            }
            if (this.worryFreeMoveSuiteConfigData.Exists(adminDto.AgentRecord.AgentRecordId, requestDto.ProvinceCode, requestDto.CityCode, requestDto.CountyCode, requestDto.VehicleBusinessMappingId).GetAwaiter().GetResult())
            {
				throw new ArgumentException("此套餐配置已存在!");
            }
			var vehicleBusinessMappingEntity = this.vehicleBusinessMappingData.GetEntity(requestDto.VehicleBusinessMappingId).GetAwaiter().GetResult();
			var entity = requestDto.As<WorryFreeMoveSuiteConfigEntity>();
			entity.CreateAdminName = adminDto.FullName;
			entity.CreateAdminId = adminDto.AdminId;
			entity.AgentRecordId = adminDto.AgentRecord.AgentRecordId;
			entity.VehicleTypeId = vehicleBusinessMappingEntity.VehicleTypeId;
			return this.worryFreeMoveSuiteConfigData.Add(entity).GetAwaiter().GetResult().As<WorryFreeMoveSuiteConfigDto>();
		}
		#endregion

		#region 修改无忧搬家套餐配置
		public WorryFreeMoveSuiteConfigDto Update(AdminDto adminDto,WorryFreeMoveSuiteConfigPutDto putDto)
		{
			if (adminDto.AgentRecord == null)
			{
				throw new ArgumentException("非代理商无法执行此操作!");
			}
			if (!this.Exists(putDto.WorryFreeMoveSuiteConfigId))
			{
				throw new ArgumentException("此记录不存在!");
			}
			if (!this.vehicleBusinessMappingData.Exists(putDto.VehicleBusinessMappingId).GetAwaiter().GetResult())
			{
				throw new ArgumentException("车辆业务配置信息不存在!");
			}
			var oldEntity = this.worryFreeMoveSuiteConfigData.GetEntity(adminDto.AgentRecord.AgentRecordId, putDto.ProvinceCode, putDto.CityCode, putDto.CountyCode, putDto.VehicleBusinessMappingId).GetAwaiter().GetResult();
			if (oldEntity!=null)
			{
				if (oldEntity.WorryFreeMoveSuiteConfigId != putDto.WorryFreeMoveSuiteConfigId)
				{
					throw new ArgumentException("此套餐配置已存在!");
				}
			}
			var vehicleBusinessMappingEntity = this.vehicleBusinessMappingData.GetEntity(putDto.VehicleBusinessMappingId).GetAwaiter().GetResult();
			var entity = putDto.As<WorryFreeMoveSuiteConfigEntity>();
			entity.EditAdminName = adminDto.FullName;
			entity.EditAdminId = adminDto.AdminId;
			entity.AgentRecordId = adminDto.AgentRecord.AgentRecordId;
			entity.VehicleTypeId = vehicleBusinessMappingEntity.VehicleTypeId;
			var result = this.worryFreeMoveSuiteConfigData.Update(entity).GetAwaiter().GetResult().As<WorryFreeMoveSuiteConfigDto>();
   //         if (result != null)
   //         {
			//	var suiteBuesinessList = this.vehicleSuiteBusinessConfigData.GetList(entity.AgentRecordId).GetAwaiter().GetResult();
			//	var worryFreeSuiteEntity = suiteBuesinessList.SingleOrDefault(p => p.AgentRecordId == entity.AgentRecordId && p.SuiteBusinessType == VehicleSuiteBusinessType.WorryFreeMove && p.CountyCode == entity.CountyCode);
   //             if (worryFreeSuiteEntity != null)
   //             {
			//		var worryFreeSuitList = this.worryFreeMoveSuiteConfigData.GetList(entity.AgentRecordId,entity.CountyCode).GetAwaiter().GetResult();
			//		worryFreeSuiteEntity.SourceFee = worryFreeSuitList.OrderBy(p=>p.)

			//	}
			//}
			string cacheKey = this.redisService.GetKey(key, entity.WorryFreeMoveSuiteConfigId);
			this.redisService.DeleteAsync(cacheKey);
			return result;
		}
		#endregion

		#region 删除无忧搬家套餐配置
		public bool Delete(AdminDto adminDto,int worryFreeMoveSuiteConfigId)
		{
			if (adminDto.AgentRecord == null)
			{
				throw new ArgumentException("非代理商无法执行此操作!");
			}
			if (!this.Exists(worryFreeMoveSuiteConfigId))
			{
				throw new ArgumentException("此记录不存在!");
			}
			var entity =  this.Get(worryFreeMoveSuiteConfigId);
			
            if (entity.AgentRecordId != adminDto.AgentRecord.AgentRecordId)
            {
				throw new ArgumentException("您无权删除此套餐配置!");
            }
			var result = this.worryFreeMoveSuiteConfigData.Delete(worryFreeMoveSuiteConfigId).GetAwaiter().GetResult();
			string cacheKey = this.redisService.GetKey(key, worryFreeMoveSuiteConfigId);
			this.redisService.DeleteAsync(cacheKey);
			return result;
		}
		#endregion

		#region 获取无忧搬家套餐配置
		public WorryFreeMoveSuiteConfigDto Get(int worryFreeMoveSuiteConfigId)
		{
			string cacheKey = this.redisService.GetKey(key, worryFreeMoveSuiteConfigId);
			var result = this.redisService.TryGet(cacheKey, () =>
			{
				var data = this.worryFreeMoveSuiteConfigData.GetEntity(worryFreeMoveSuiteConfigId).GetAwaiter().GetResult();
				return data;
			}, TimeSpan.FromDays(1));
			return result.As<WorryFreeMoveSuiteConfigDto>();
		}
		#endregion

		#region 获取无忧搬家套餐配置列表
		public IEnumerable<WorryFreeMoveSuiteConfigViewDto> GetList(long agentRecordId, string countyCode)
		{
			string cacheKey = this.redisService.GetKey(key, agentRecordId,countyCode);
			var result = this.redisService.TryGet(cacheKey, () =>
			{
				return this.worryFreeMoveSuiteConfigData.GetList(agentRecordId, countyCode).GetAwaiter().GetResult();
			}, TimeSpan.FromDays(1));
			return result.As<IEnumerable<WorryFreeMoveSuiteConfigViewDto>>();
		}
		#endregion

		#region 获取有无忧搬家套餐配置的代理商区域列表
		public IEnumerable<AgentAreaTreeDto> GetAgenAreaTreeList()
		{
			string cacheKey = this.redisService.GetKey(key, "AgentAreaTree");
			var result = this.redisService.TryGet(cacheKey, () =>
			{
				var list = this.worryFreeMoveSuiteConfigData.GetList().Result;
				var provinceGroupList = list.GroupBy(p => p.ProvinceCode);
				List<AgentAreaTreeDto> tree = new List<AgentAreaTreeDto>();
				foreach (var item in provinceGroupList)
				{
					AgentAreaTreeDto province = new AgentAreaTreeDto();
					province.ProvinceCode = item.Key;
					province.ProvinceName = item.First().ProvinceName;
					List<AgentCityTreeDto> cityList = new List<AgentCityTreeDto>();
					var cityGroupList = item.GroupBy(p => p.CityCode);
					foreach (var cityItem in cityGroupList)
					{
						AgentCityTreeDto city = new AgentCityTreeDto();
						city.CityCode = cityItem.Key;
						city.CityName = cityItem.First().CityName;
						List<AgentCountyTreeDto> countyList = new List<AgentCountyTreeDto>();
						var countyGroupList = cityItem.GroupBy(p => p.CountyCode);
						foreach (var countyItem in countyGroupList)
						{
							AgentCountyTreeDto county = new AgentCountyTreeDto();
							county.CountyCode = countyItem.Key;
							county.CountyName = countyItem.First().CountyName;
							countyList.Add(county);
						}
						city.Children = countyList;
						cityList.Add(city);
					}
					province.Children = cityList;
					tree.Add(province);

				}
				return tree;
			}, TimeSpan.FromDays(1));
			return result;
		}
		#endregion

		#region 获取无忧搬家套餐配置分页
		public PageableList<WorryFreeMoveSuiteConfigDto> Query(long? agentRecordId, string suiteName, string provinceCode, string cityCode, string countyCode, bool? enabled, DateTime? start, DateTime? end, string sortName, bool? ascending, int pageIndex, int pageSize)
		{
			string cacheKey = this.redisService.GetKey(key, agentRecordId, suiteName, provinceCode, cityCode, countyCode, enabled, start, end, sortName, ascending, pageIndex, pageSize);
			var result = this.redisService.TryGet(cacheKey, () =>
			{
				var data = this.worryFreeMoveSuiteConfigData.Query(agentRecordId, suiteName, provinceCode, cityCode, countyCode, enabled, start, end, sortName, ascending, pageIndex, pageSize).GetAwaiter().GetResult();
				return new PageableList<WorryFreeMoveSuiteConfigDto>
				{
					Count = data.Item2,
					Items = data.Item1.As<IEnumerable<WorryFreeMoveSuiteConfigDto>>(),
					PageIndex = pageIndex,
					PageSize = pageSize,
					ServerTime = DateTime.Now
				};
			}, TimeSpan.FromMinutes(30));

			return result;
		}
		#endregion

		#region 启用无忧搬家套餐配置
		public bool Enabled(AdminDto adminDto,int worryFreeMoveSuiteConfigId)
		{
			if (adminDto.AgentRecord == null)
			{
				throw new ArgumentException("非代理商无法执行此操作!");
			}
			if (!this.Exists(worryFreeMoveSuiteConfigId))
			{
				throw new ArgumentException("此记录不存在!");
			}
			var entity = this.Get(worryFreeMoveSuiteConfigId);

			if (entity.AgentRecordId != adminDto.AgentRecord.AgentRecordId)
			{
				throw new ArgumentException("您无权删除此套餐配置!");
			}
			var result = this.worryFreeMoveSuiteConfigData.Enabled(worryFreeMoveSuiteConfigId,adminDto.AdminId,adminDto.FullName).GetAwaiter().GetResult();
			string cacheKey = this.redisService.GetKey(key, worryFreeMoveSuiteConfigId);
			this.redisService.DeleteAsync(cacheKey);
			return result;
		}
		#endregion

		#region 禁用无忧搬家套餐配置
		public bool Disabled(AdminDto adminDto, int worryFreeMoveSuiteConfigId)
		{
			if (adminDto.AgentRecord == null)
			{
				throw new ArgumentException("非代理商无法执行此操作!");
			}
			if (!this.Exists(worryFreeMoveSuiteConfigId))
			{
				throw new ArgumentException("此记录不存在!");
			}
			var entity = this.Get(worryFreeMoveSuiteConfigId);

			if (entity.AgentRecordId != adminDto.AgentRecord.AgentRecordId)
			{
				throw new ArgumentException("您无权删除此套餐配置!");
			}
			var result = this.worryFreeMoveSuiteConfigData.Disabled(worryFreeMoveSuiteConfigId, adminDto.AdminId, adminDto.FullName).GetAwaiter().GetResult();
			string cacheKey = this.redisService.GetKey(key, worryFreeMoveSuiteConfigId);
			this.redisService.DeleteAsync(cacheKey);
			return result;
		}
		#endregion
	}
}